package com.kaizeli.website.util;

import com.kaizeli.website.constant.JwtConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;


public class JwtUtil {
    public static String generateToken(String username, boolean isAdmin) {
        return generateToken(username, isAdmin, JwtConstant.EXPIRATION_TIME);
    }
    
    public static String generateToken(String username, boolean isAdmin, long expirationTime) {
        return Jwts.builder()
                .setSubject(username)
                .claim("admin", isAdmin)
                .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
                .signWith(SignatureAlgorithm.HS512, JwtConstant.SECRET_KEY)
                .compact();
    }

    public static Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(JwtConstant.SECRET_KEY)
                .parseClaimsJws(token.replace(JwtConstant.TOKEN_PREFIX, ""))
                .getBody();
    }

    public static String getUsernameFromToken(String token) {
        return getClaimsFromToken(token).getSubject();
    }

    public static boolean isAdminFromToken(String token) {
        return getClaimsFromToken(token).get("admin", Boolean.class);
    }

    public static boolean validateToken(String token) {
        try {
            getClaimsFromToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



}
